import taskService from "@/api/services/taskService";
import type { TaskItem } from "@/api/services/taskService";
import { IconButton } from "@/components/icon";
import { Iconify } from "@/components/icon";
import {
	Button,
	Card,
	Modal,
	Space,
	Table,
	Tag,
	Tooltip,
	Typography,
	message,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useState } from "react";
import TaskModal from "./task-modal";

const statusMap = {
	0: { text: "待审核", color: "default" },
	1: { text: "正常", color: "success" },
	2: { text: "已拒绝", color: "error" },
};

export default function TaskListPage() {
	const [loading, setLoading] = useState(false);
	const [tasks, setTasks] = useState<TaskItem[]>([]);
	const [total, setTotal] = useState(0);
	const [currentPage, setCurrentPage] = useState(1);
	const [pageSize, setPageSize] = useState(10);
	const [modalVisible, setModalVisible] = useState(false);
	const [editingTask, setEditingTask] = useState<TaskItem | undefined>();
	const [detailVisible, setDetailVisible] = useState(false);
	const [currentTask, setCurrentTask] = useState<TaskItem>();

	const fetchTasks = async (page = 1, limit = 10) => {
		setLoading(true);
		try {
			const res = await taskService.taskList({ page, limit });
			setTasks(res.items);
			setTotal(res.total);
		} catch (error) {
			message.error("获取任务列表失败");
		} finally {
			setLoading(false);
		}
	};

	useEffect(() => {
		fetchTasks(currentPage, pageSize);
	}, [currentPage, pageSize]);

	const handleAddTask = () => {
		setEditingTask(undefined);
		setModalVisible(true);
	};

	const handleEditTask = (task: TaskItem) => {
		setEditingTask(task);
		setModalVisible(true);
	};

	const handleModalOk = () => {
		setModalVisible(false);
		fetchTasks(currentPage, pageSize);
	};

	const handleViewDetail = async (task: TaskItem) => {
		try {
			const detail = await taskService.taskInfo(task.id);
			setCurrentTask(detail);
			setDetailVisible(true);
		} catch (error) {
			message.error("获取任务详情失败");
		}
	};

	const columns: ColumnsType<TaskItem> = [
		{
			title: "任务标题",
			dataIndex: "title",
			key: "title",
			render: (text) => <Typography.Text strong>{text}</Typography.Text>,
		},
		{
			title: "类别",
			dataIndex: ["category", "name"],
			key: "category",
			render: (text) => <Tag color="cyan">{text}</Tag>,
		},
		{
			title: "单价(元)",
			dataIndex: "price",
			key: "price",
			render: (price) => <Typography.Text>¥{price}</Typography.Text>,
		},
		{
			title: "状态",
			dataIndex: "status",
			key: "status",
			render: (status) => (
				<Tag color={statusMap[status]?.color || "default"}>
					{statusMap[status]?.text || "未知"}
				</Tag>
			),
		},
		{
			title: "创建时间",
			dataIndex: "createtime",
			key: "createtime",
			render: (time) => new Date(time * 1000).toLocaleString(),
		},
		{
			title: "更新时间",
			dataIndex: "updatetime",
			key: "updatetime",
			render: (time) => new Date(time * 1000).toLocaleString(),
		},
		{
			title: "操作",
			key: "actions",
			render: (_, record) => (
				<Space>
					<Tooltip title="查看详情">
						<IconButton onClick={() => handleViewDetail(record)}>
							<Iconify icon="solar:eye-bold" />
						</IconButton>
					</Tooltip>

					<Tooltip title="编辑">
						<IconButton onClick={() => handleEditTask(record)}>
							<Iconify icon="solar:pen-bold" />
						</IconButton>
					</Tooltip>
				</Space>
			),
		},
	];

	return (
		<>
			<Card>
				<div className="mb-4 flex justify-between items-center">
					<Typography.Title level={4}>任务列表</Typography.Title>
					<Button
						type="primary"
						icon={<Iconify icon="solar:add-circle-bold" />}
						onClick={handleAddTask}
					>
						新建任务
					</Button>
				</div>
				<Table
					columns={columns}
					dataSource={tasks}
					rowKey="id"
					loading={loading}
					pagination={{
						current: currentPage,
						pageSize: pageSize,
						total: total,
						onChange: (page, pageSize) => {
							setCurrentPage(page);
							setPageSize(pageSize);
						},
					}}
				/>
			</Card>

			<TaskModal
				open={modalVisible}
				title={editingTask ? "编辑任务" : "新建任务"}
				initialValues={editingTask}
				onOk={handleModalOk}
				onCancel={() => setModalVisible(false)}
			/>

			<Modal
				open={detailVisible}
				title="任务详情"
				footer={null}
				onCancel={() => setDetailVisible(false)}
			>
				{currentTask && (
					<div className="space-y-4">
						<div>
							<Typography.Text type="secondary">任务标题：</Typography.Text>
							<Typography.Text strong>{currentTask.title}</Typography.Text>
						</div>
						<div>
							<Typography.Text type="secondary">类别：</Typography.Text>
							<Tag color="cyan">{currentTask.category?.name}</Tag>
						</div>
						<div>
							<Typography.Text type="secondary">单价：</Typography.Text>
							<Typography.Text>¥{currentTask.price}</Typography.Text>
						</div>
						<div>
							<Typography.Text type="secondary">状态：</Typography.Text>
							<Tag color={statusMap[currentTask.status]?.color}>
								{statusMap[currentTask.status]?.text}
							</Tag>
						</div>
						<div>
							<Typography.Text type="secondary">创建时间：</Typography.Text>
							<Typography.Text>
								{currentTask.createtime &&
									new Date(currentTask.createtime * 1000).toLocaleString()}
							</Typography.Text>
						</div>
						<div>
							<Typography.Text type="secondary">更新时间：</Typography.Text>
							<Typography.Text>
								{currentTask.updatetime &&
									new Date(currentTask.updatetime * 1000).toLocaleString()}
							</Typography.Text>
						</div>
					</div>
				)}
			</Modal>
		</>
	);
}
